<?php

declare (strict_types=1);

namespace tmcore\base;

use tmcore\exceptions\ValidateException;
use think\exception\HttpResponseException;
use think\Response;
use think\Validate;
use tmcore\traits\JsonTrait;

/**
 * 验证器基类
 */
abstract class BaseValidate extends Validate
{
    use JsonTrait;

    public string $method = 'GET';

    /**
     *  post请求方式
     * @throws ValidateException
     */
    public function post()
    {
        if (!$this->request->isPost()) {
            throw new ValidateException('请求方式错误，请使用post请求方式',108);
        }
        $this->method = 'POST';
        return $this;
    }

    /**
     *  get请求方式
     * @throws ValidateException
     */
    public function get()
    {
        if (!$this->request->isGet()) {
            throw new ValidateException('请求方式错误，请使用get请求方式',108);
        }
        return $this;
    }

    /**
     *  delete请求方式
     * @throws ValidateException
     */
    public function delete()
    {
        if (!$this->request->isDelete()) {
            throw new ValidateException('请求方式错误，请使用delete请求方式',108);
        }
        $this->method = 'DELETE';
        return $this;
    }

    /**
     * 验证参数
     *
     * @param string $scene 场景验证
     * @param array $data 扩展的验证参数
     * @return mixed
     */
    public function checkParam($scene = '', array $data = [])
    {
        if (request()->isGet()) {
            $params = request()->get();
        } elseif (request()->isDelete()) {
            $params = request()->param();
        } else {
            $params = request()->post();
        }
        if (!empty($data)) {
            $params = array_merge($params, $data);
        }

        if (!($scene ? $this->scene($scene)->check($params) : $this->check($params))) {
            $exception = is_array($this->error)
                ? implode(';', $this->error) : $this->error;

            $data = array('code'=>10000, 'msg'=>$exception, 'data'=>[]);
            $response = Response::create($data, 'json', 200);
            throw new HttpResponseException($response);
        }

        return $params;
    }
}